﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace Microweb.Utils
{
    /// <summary>
    /// 8.3文件名格式
    /// </summary>
    public class EightDotThreeFormat
    {
        private string _fullPath;
        /// <summary>
        /// Initializes a new instance of the EightDotThreeFormat class.
        /// </summary>
        /// <param name="fullPath"></param>
        public EightDotThreeFormat(string fullPath)
        {
            _fullPath = fullPath;
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern int GetShortPathName(
                 [MarshalAs(UnmanagedType.LPTStr)]
                   string path,
                 [MarshalAs(UnmanagedType.LPTStr)]
                   StringBuilder shortPath,
                 int shortPathLength
                 );
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern int GetLongPathName(
                 [MarshalAs(UnmanagedType.LPTStr)]
                   string path,
                 [MarshalAs(UnmanagedType.LPTStr)]
                   StringBuilder longPath,
                 int longPathLength
                 );
    
        public static string ToShortPath(string longPath)
        {
            var edtf = new EightDotThreeFormat(longPath);
            return edtf.ToShortPath();            
        }

        public static string ToLongPath(string shortPath)
        {
            var edtf = new EightDotThreeFormat(shortPath);
            return edtf.ToLongPath();
        }

        /// <summary>
        /// 转换为短路径
        /// </summary>
        /// <remarks>
        /// 例如：
        /// D:\DOTNET~1
        /// D:\DOTNET~1\SYSTEM~1.PDB\CD75D0~1\SYSTEM~1.PDB
        /// </remarks>
        /// <returns></returns>
        public string ToShortPath()
        {
            StringBuilder shortPath = new StringBuilder(255);
            GetShortPathName(_fullPath, shortPath, shortPath.Capacity);
            return shortPath.ToString();
        }

        /// <summary>
        /// 转换为长路径
        /// <remarks>
        /// 例如:D:\DotNetSymbols
        /// </remarks>
        /// </summary>
        /// <returns></returns>
        public string ToLongPath()
        {
            StringBuilder longPath = new StringBuilder(255);
            GetLongPathName(_fullPath, longPath, longPath.Capacity);
            return longPath.ToString();
        }
    }
}
